<template>
  <div class="container">
    <el-row class="topTitleBox">
      <el-col class="topTitle">
        <i class="icon iconfont iconfanhui1" @click="goBack"></i>
        <span class="el-dropdown-link titleStyle">
          {{ projectName }}
        </span>
        <span class="status">已开工</span>
      </el-col>
    </el-row>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="164px"
        class="demo-formData"
      >
        <el-row>
          <el-form-item label="受理机构：" class="row-padding-bottom">
            {{ formData.bureau }}
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item
            prop="insNo"
            label="单位编号："
            class="row-padding-bottom"
          >
            <el-input
              class="dialogSingleInp"
              v-model="formData.insNo"
              placeholder="请输入单位编号"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            prop="insDate"
            label="参保时间："
            class="row-padding-bottom"
          >
            <el-date-picker
              class="dialogSingleInp"
              v-model="formData.insDate"
              type="date"
              placeholder="选择日期"
              clearable
              :style="{ width: '100%' }"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item
            prop="companyIndex"
            label="参保单位："
            class="row-padding-bottom"
          >
            <el-select
              v-model="companyIndex"
              filterable
              placeholder="请选择"
              class="dialogSingleInp"
              clearable
            >
              <el-option
                v-for="(item, index) in companyList"
                :key="item.id"
                :label="item.companyName"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            prop="insurancedName"
            label="参保人员："
            class="row-padding-bottom"
          >
            <div class="uploadBox">
              <el-link type="success" @click="showEmployeeList">添加</el-link>
              <!-- <el-button round class="uploadImg" @click="showEmployeeList">添加</el-button> -->
            </div>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="upLoadFile"
              :label="titleTip"
              class="upLoadDomContainer"
              v-model="formData.fileList"
            >
              <div class="tips" v-if="isHsUser()">
                请上传工伤保险参保登记表（<el-link
                  type="primary"
                  @click="typicalDrawing('1')"
                  >查看示例图</el-link
                >)、税收完税证明（<el-link
                  type="primary"
                  @click="typicalDrawing('2')"
                  >查看示例图</el-link
                >)或社会保险单位基本情况表（<el-link
                  type="primary"
                  @click="typicalDrawing('3')"
                  >查看示例图</el-link
                >)作为参保凭证附件格式支持png，jpg，jpeg，
                doc，docx，xls，xlsx，pdf，最多上传10个附件
              </div>
              <uploadAnnex
                @getFileList="getFileListInsurance"
                :limitationFactor="limitationFactorInsurance"
                @getFile="getFileInsurance"
                :upLoadFile="upLoadFile"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-model="formData.fileList">
            <!-- <elementImage :upLoadFile="upLoadFile"   :srcList="srcList" :oldSrcList="oldSrcList" @changeSrcList="changeSrcList"></elementImage> -->
            <uploadResult
              style="margin-left: 120px"
              :resultList="upLoadFile"
              @callBackResult="getFileInsurance"
            />
          </el-col>
        </el-row>
        <el-form-item class="submitBox">
          <el-button
            type="primary"
            class="commonBut saveBtn"
            :loading="isSaveLoading"
            @click="saveForm"
            >保存</el-button
          >
          <el-button class="commonBut" @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
      <!-- 图片预览 -->
      <el-image
        class="previewImg"
        style="width: 56px; height: 0px"
        src="../../../static/img/monitorHome/card.png"
        :preview-src-list="typicalDrawingSrcList"
        id="seeExampleBox"
      ></el-image>
    </div>

    <el-dialog
      title="添加参保人员"
      :visible.sync="addDialogFormVisible"
      :show-close="false"
      :close-on-click-modal="false"
      width="750px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <div>
        <el-transfer
          filterable
          :filter-method="filterMethod"
          :titles="['参保人员', '已选择的人员']"
          class="insuranceTransfer"
          filter-placeholder="请输入姓名或身份证号码"
          v-model="insurancedName"
          :data="insuranceData"
        >
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd" class="cancel">取 消</el-button>
        <el-button type="primary" class="save" @click="addInsured"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 如需审核 弹窗 -->
    <el-dialog
      title="温馨提示"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="750px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <div class="dialogContent">
        提交后需要劳动监察部门审核通过，方可视为成功备案
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog" class="cancel">取 消</el-button>
        <el-button type="primary" class="save" @click="affirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import common from '../../kits/common'

export default {
  name: 'addInsurance',
  components: {},
  data() {
    const generateData = (_) => {
      const data = []
      const users = [
        { name: '张三', cardId: '254****253', id: 0 },
        { name: '李四', cardId: '254****254', id: 1 },
        { name: '王五', cardId: '254****255', id: 2 },
        { name: '李欣', cardId: '254****256', id: 3 },
      ]
      users.forEach((item) => {
        data.push({
          label: item.name + '  ' + item.cardId,
          key: item.id,
        })
      })
      return data
    }
    var checkCompanyIndex = (rule, value, callback) => {
      var that = this
      if (that.companyIndex.length == 0) {
        return callback(new Error('参保单位不能为空'))
      } else {
        callback()
      }
    }
    var checkInsurancedName = (rule, value, callback) => {
      var that = this
      if (this.isCzUser()) {
        callback()
        return
      }
      if (that.insurancedName.length == 0) {
        return callback(new Error('参保人员不能为空'))
      } else {
        callback()
      }
    }
    var checkUpLoadFile = (rule, value, callback) => {
      var that = this
      if (this.isCzUser()) {
        if (that.upLoadFile.length == 0) {
          return callback(new Error('完税证明不能为空'))
        } else {
          callback()
        }
      } else {
        if (that.upLoadFile.length == 0) {
          return callback(new Error('参保凭证不能为空'))
        } else {
          callback()
        }
      }
    }

    return {
      isHover: false,
      insuranceData: [], //generateData(),
      insurancedName: [],
      filterMethod(query, item) {
        return item.label.indexOf(query) > -1
      },
      projectId: '',
      titleTip: '参保凭证：',
      projectName: '',
      companyList: [],
      company: {},
      addDialogFormVisible: false,

      tableList: [],
      currentPage: 1,
      pageSize: 30,
      currentTotal: 0,

      isShow: false, //列表加载
      // loading: true, //列表loading
      canLogin: false, //保存loading

      upLoadFile: [],
      oldSrcList: [],
      dialogImageUrl: '',
      srcList: [],
      companyIndex: '',
      isSaveLoading: false, // 保存loading
      formData: {
        insNo: '', //保险单号  -----必传
        insDate: '', //参保日期  -----必传
        projectId: '', //项目id  -----必传
        companyName: '', //参保企业名（不包含括号内） -----必传
        companyType: '', //参保企业类型 01 05 10  -----必传
        uscc: '', //参保企业uscc  -----必传
        bureau: '', //受理机构  -----必传
        batchNo: '1', //批次号  -----必传
        fileList: [], //文件对象数组  -----非必传
        employeeList: [],
      },

      filterField: {
        searchText: '',
        insId: '',
      },
      formRules: {
        insNo: [
          {
            required: true,
            //   pattern: /^[0-9]*$/,
            pattern: /^[^\u4e00-\u9fa5]{0,}$/,
            message: '请输入正确的单位编号',
            trigger: 'blur',
          },
        ],
        insDate: [
          {
            required: true,
            message: '参保时间不能为空',
            trigger: 'blur',
          },
        ],
        companyIndex: [
          { required: true, validator: checkCompanyIndex, trigger: 'change' },
        ],
        insurancedName: [
          {
            required: true,
            validator: checkInsurancedName,
            trigger: 'blur',
          },
        ],
        upLoadFile: [
          {
            required: true,
            validator: checkUpLoadFile,
            trigger: 'blur',
          },
        ],
      },
      addInsuredPersonnel: '', //添加参保人员点击确定保存数据
      // 保单
      limitationFactorInsurance: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        messagetip: '仅支持上传png、jpg、jpeg格式文件', //自定义报错提示语
        fileId: 'salaryExcelInsurance', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelInsuranceForm', //自定义id解决一个页面包含多个上传附件
        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M', //自定义报错提示语
        // methodTip:"请上传保单回执，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件", //自定义上传文件提示
        methodTip: '',
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      typicalDrawingSrcList: [],
      dialogFormVisible: false,
      needCheck: '', //是否需要审核
      insId: '',
      // companyName:"", //参保单位
      // insNo:"",//单位编号
    }
  },
  activated: function () {},
  created() {
    this.projectId = this.$route.query.projectId
    this.projectName = this.$route.query.projectName
    this.needCheck = this.$route.query.needCheck
    this.insId = this.$route.query.insId

    this.getCompanyListData()
    // this.formData = {};
    //滁州参保人员为非必填
    if (this.isCzUser()) {
      this.formRules.insurancedName[0].required = false
      this.titleTip = '完税证明：'
      this.limitationFactorInsurance.methodTip =
        '请上传完税证明，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件'
    }
    if (this.isHsUser()) {
      this.formRules.insurancedName[0].required = true
      this.limitationFactorInsurance.methodTip = ''
    } else {
      this.formRules.insurancedName[0].required = true
      this.limitationFactorInsurance.methodTip =
        '请上传保单回执，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件'
    }
  },
  methods: {
    mouseroverInput() {
      this.isHover = true
    },
    mouserleaveInput() {
      this.isHover = false
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /**
     * @description: 改变图片地址
     */
    changeSrcList(val) {
      this.srcList = val
    },
    getCompanyListData() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/insdetail/expand/projectInfo',
        data: { projectId: this.projectId },
      }).then((resp) => {
        if (!resp.data.hasError) {
          this.companyList = resp.data.result.companyList
          this.formData.bureau = resp.data.result.bureau //参保企业uscc  -----必传
          if (this.insId && this.needCheck) {
            this.getDetail()
          }
        } else {
          this.$message({
            showClose: true,
            duration: 3000,
            message: resp.data.errorMsg,
            type: 'error',
          })
        }
      })
      // .catch(resp => {
      //   this.$message.error("数据获取失败");
      // });
    },
    getDetail() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/ins/expand/detail',
        data: { insId: this.insId },
      }).then((resp) => {
        if (!resp.data.hasError) {
          this.formData.companyName = resp.data.result.companyName
          this.formData.insNo = resp.data.result.insNo
          //  下拉框选中
          this.companyList.forEach((item, index) => {
            if (
              item.companyName == resp.data.result.companyName &&
              item.type == resp.data.result.companyType
            ) {
              this.companyIndex = index
            }
          })
        } else {
          this.$message({
            showClose: true,
            duration: 3000,
            message: resp.data.errorMsg,
            type: 'error',
          })
        }
      })
      // .catch(resp => {
      //   this.$message.error("数据获取失败");
      // });
    },
    saveForm() {
      this.$refs.formData.validate((valid) => {
        this.formData.fileList = JSON.stringify(this.upLoadFile) //this.upLoadFile;
        var employeeTempList = []
        if (this.addInsuredPersonnel) {
          this.addInsuredPersonnel.forEach((item) => {
            employeeTempList.push(this.insuranceData[item]['item'].contractId)
          })
        }
        if (this.isCzUser() && employeeTempList.length < 1) {
          employeeTempList = [0]
        }

        //this.formData.employeeList= employeeTempList;//JSON.stringify(employeeTempList);

        this.formData.employeeList = JSON.stringify(employeeTempList)
        this.formData.projectId = this.projectId //项目id  -----必传
        if (this.companyList[this.companyIndex]) {
          this.formData.companyName =
            this.companyList[this.companyIndex].companyName //参保企业名（不包含括号内） -----必传
          this.formData.companyType = this.companyList[this.companyIndex].type //参保企业类型 01 05 10  -----必传
          this.formData.uscc = this.companyList[this.companyIndex].uscc //参保企业uscc  -----必传
        }

        if (valid) {
          this.isSaveLoading = true
          this.saveFormInfo()
        } else {
          return false
        }
      })
    },
    saveFormInfo() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/ins/expand/addins',
        data: this.formData,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            // this.$message({
            //   type: "success",
            //   message: "保存成功"
            // });
            this.formVisible = false
            if (this.needCheck && !this.insId) {
              this.dialogFormVisible = true
            } else {
              this.goBack()
            }
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          // this.$message.error("数据获取失败");
          //this.$message.error("保存失败");
          this.isSaveLoading = false
        })
    },
    goBack() {
      this.$refs['formData'].resetFields()
      this.$router.push({
        path: '/home/insurance/insurance',
        name: 'insurance',
        query: {
          projectId: this.projectId,
          projectName: this.projectName,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/insurance/insurance',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    showEmployeeList(id) {
      this.filterField.insId = id
      this.searchList()
      this.addDialogFormVisible = true
    },

    searchList() {
      this.insuranceData = [] //generateData(),
      this.axios({
        method: 'POST',
        url: 'api-e/cs/insdetail/expand/employeelist',
        data: {
          searchText: this.filterField.searchText,
          projectId: this.projectId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            //console.log(response.data.result)
            var list = response.data.result
            list.forEach((item, index) => {
              this.insuranceData.push({
                label: item.name + '  ' + item.idcard,
                key: index,
                item: item,
              })
            })
          }
        })
        .catch((error) => {
          this.$message.error('数据获取失败')
        })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.searchList()
    },
    handleCurrentChange(val) {
      this.currentPage = val

      this.searchList()
    },
    cancelAdd() {
      if (this.addInsuredPersonnel) {
        this.insurancedName = this.addInsuredPersonnel
      } else {
        if (this.insurancedName) {
          this.insurancedName = []
        }
      }
      this.addDialogFormVisible = false
    },
    addInsured() {
      this.addInsuredPersonnel = this.insurancedName
      this.addDialogFormVisible = false
    },
    getFileListInsurance(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    getFileInsurance(val) {
      this.upLoadFile = val
    },
    cancelDialog() {
      this.dialogFormVisible = false
      this.goBack()
    },
    affirm() {
      this.dialogFormVisible = false
      this.goBack()
    },
    // 查看示例
    typicalDrawing(index) {
      var url = common.uploadUrl + '/statics/template/INS' + index + '.png'
      this.typicalDrawingSrcList = [url]
      $('#seeExampleBox').click()
    },
  },
}
</script>
<style scoped lang="less">
.insuranceTransfer {
  /deep/ .el-transfer-panel {
    //  width: 220px;
    width: 40.5%;
  }
  /deep/ .el-transfer__button {
    display: block;
    margin: 10px 0 0 0 !important;
    padding: 8px 20px;
  }
  /deep/ .el-icon-arrow-left,
  /deep/ .el-icon-arrow-right {
    font-size: 20px;
  }
}

.topTitle {
  height: 50px;
  background-color: #fff;
  font: bold 18px/50px Microsoft YaHei;
  border-bottom: 1px solid #e3e7e9;
  padding: 0 24px;
  .titleStyle {
    color: #333;
    font-size: 18px;
    .el-icon-caret-bottom {
      color: #71818e;
    }
  }
  .status {
    display: inline-block;
    width: 48px;
    height: 20px;
    line-height: 20px;
    margin-bottom: 10px;
    background: #009588;
    color: #fff;
    text-align: center;
    font-size: 12px;
    // border-radius: 4px;
  }
  .saveBtn {
    margin-right: 24px;
    margin-top: 15.5px;
  }
}
.activedBtn {
  background-color: #f4f4f4;
}
.container {
  .mainCon {
    height: calc(100% - 67px);
    padding: 40px 0;
    padding-right: 80px;
    overflow-y: auto;
    .labelStyMin {
      padding-left: 0px !important;
      min-width: 130px;
    }
    .labelStyMax {
      padding-left: 0px !important;
      margin-left: 5px;
      min-width: 155px;
    }
    .submitBox {
      text-align: left;
      margin-top: 18px;
    }
    .picStyle {
      width: 116px;
      margin-right: 60px;
      img {
        width: 100%;
      }
    }
    .uploadBox {
      position: relative;
      .uploadImg {
        width: 96px;
        height: 36px;
        color: #009588;
        border: 1px solid #009588;
        line-height: 10px;
      }
      .uploadImgState {
        font-size: 14px;
        color: #999999;
        margin-left: 12px;
      }
      .upLoadDom {
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        border-radius: 18px;
        input {
          width: 96px;
          height: 36px;
          border-radius: 18px;
          vertical-align: middle;
        }
        &:hover {
          .uploadImg {
            background-color: #0ff;
          }
        }
      }
    }
    .imgStyle {
      padding-left: 130px;
      li {
        position: relative;
        margin-right: 20px;
        margin-top: 10px;
        i {
          position: absolute;
          right: -6px;
          top: -10px;
          font-size: 20px;
        }
      }
    }
  }
}
form.el-form.demo-formData {
  // max-width: 800px;
  display: inline-block;
  text-align: left;
  // .el-input,
  // .el-select{
  //   width: 320px !important;
  // }
  .selectWidth {
    width: 100%;
  }
}
.el-main .el-form-item {
  margin-bottom: 20px;
}
.saveBtn {
  background-color: #009588;
  border-color: #009588;
  color: #fff;
}

.tips {
  color: #999;
  line-height: 20px;
  margin-bottom: 22px;
  margin-top: 8px;
  a {
    color: #265faa;
  }
}
</style>
<style>
.upLoadDomContainer .el-form-item__content {
  line-height: 36px !important;
}
</style>
